#!/usr/bin/perl
# 2012/11/27 Remove potential self ligation product


use strict;
use warnings;
use IO::File;
use Getopt::Std;
use File::Basename;
use Carp qw(croak);
$| = 0;


if(@ARGV != 4 or $ARGV[0] eq '--help'){
	die "Usage : $0 -i [map file] -o [output filtered map file]\n";
}

my %opt;
getopts("i:o:", \%opt);
my $FILE_map = $opt{i};
my $FILE_out = $opt{o};

my $COUNTER_all = 0;
my $COUNTER_passed = 0;


# id chr1 loc1 direction1 quality1 hind1 hiv 2nd_loc1 chr2 loc2 direction2 quality2 hind2 hind_loc2 type(unique or repeat) number(alignable locations) locations
my $fh_out = IO::File->new($FILE_out, 'w') or die "cannot write $FILE_out: $!";
my $fh_map = IO::File->new($FILE_map) or die "cannot open $FILE_map: $!";
while($_ = $fh_map->getline()){
	s/\r?\n//;
	$COUNTER_all++;
	my ($id, $chr1, $loc1, $direction1, $mapQ1, $hinID1, $hinLoc1, $chr2, $loc2, $direction2, $mapQ2, $hinID2, $hinLoc2, $type, $num, $locations) = split /\t/;

	if($chr1 ne $chr2){
		$fh_out->print("$_\n");
		$COUNTER_passed++;
		next;
	}

	if(abs($hinLoc1 - $hinLoc2) > 20000){
		$fh_out->print("$_\n");
		$COUNTER_passed++;
	}
}
$fh_map->close();
$fh_out->close();

print "all reads: $COUNTER_all\n";
printf "passed reads: %d (%.3f)\n", $COUNTER_passed, $COUNTER_passed / $COUNTER_all * 100;